<?php

namespace app\admin\controller\chase;

use app\admin\model\chase\CouponVip;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 优惠券管理
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{
    
    /**
     * Coupon模型对象
     * @var \app\admin\model\chase\Coupon
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\chase\Coupon;
        $this->view->assign('categories', \app\admin\model\chase\CouponCategory::getCategories());
        $this->view->assign('services', \app\admin\model\chase\ModelingService::all());
        $this->view->assign("discountTypeList", $this->model->getDiscountTypeList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("onlineList", $this->model->getOnlineList());
        $this->view->assign("expiredTypeList", $this->model->getExpiredTypeList());
        $this->view->assign("buyTypeList", $this->model->getBuyTypeList());
        $this->view->assign("vipList", \app\admin\model\chase\UserVip::getVips());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['category', 'service', 'vip'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['category', 'service', 'vip'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            array_walk($list, function (&$val) {
                $val['start_time'] = $val['start_time'] ? date('Y-m-d H:i:s', $val['start_time']) : '';
                $val['end_time'] = $val['end_time'] ? date('Y-m-d H:i:s', $val['end_time']) : '';
                if ($val['discount_type'] == 2) {
                    $val['discount_amount'] = $val['discount_amount'] / 1 . '折';
                }
                //vip
                $val['vip_name'] = array_column($val['vip'], 'name');
            });
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($params['service'] && (!isset($params['service_id']) || !$params['service_id'])) {
                    $this->error('指定的服务不能为空');
                }
                if ($params['discount_type'] == 2) {
                    if ($params['discount'] < 0.1 || $params['discount'] > 10) {
                        return $this->error('折扣超出0.1 ~ 10范围');
                    }
                    $params['discount_amount'] = $params['discount'];
                }
                if (in_array($params['type'], [1, 3]) && $params['discount_type'] != 1) {
                    $this->error('满减券和现金券请选择优惠金额');
                }
                if ($params['type'] == 2 && $params['discount_type'] != 2) {
                    $this->error('折扣券请选择折扣');
                }
                if (in_array($params['type'], [1, 2, 3]) && $params['num'] > 1) {
                    $this->error('优惠券数量必须为1');
                }

                $params['total_num'] = $params['stock_num'];
                $params['start_time'] = strtotime($params['start_time']);
                $params['end_time'] = strtotime($params['end_time']);
                if ($params['expired_type'] == 1) {
                    if (!$params['start_time'] || !$params['end_time']) {
                        return $this->error('开始时间和结束时间都不能为空');
                    }
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    //会员专享
//                    if ($params['vip'][0]) {
//                        CouponVip::add($this->model->id, $params['vip']);
//                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $coupon_vips = CouponVip::getVips($ids);
        $row['start_time'] = $row['start_time'] ? date('Y-m-d H:i:s', $row['start_time']) : '';
        $row['end_time'] = $row['end_time'] ? date('Y-m-d H:i:s', $row['end_time']) : '';
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($params['service'] && (!isset($params['service_id']) || !$params['service_id'])) {
                    $this->error('指定的服务不能为空');
                }
                if ($params['discount_type'] == 2) {
                    if ($params['discount'] < 0.1 || $params['discount'] > 10) {
                        return $this->error('折扣超出0.1 ~ 10范围');
                    }
                    $params['discount_amount'] = $params['discount'];
                }
//                if (in_array($params['type'], [1, 3]) && $params['discount_type'] != 1) {
//                    $this->error('满减券和现金券请选择优惠金额');
//                }
//                if ($params['type'] == 2 && $params['discount_type'] != 2) {
//                    $this->error('折扣券请选择折扣');
//                }
//                if (in_array($params['type'], [1, 2, 3]) && $params['num'] > 1) {
//                    $this->error('优惠券数量必须为1');
//                }
                $params['total_num'] = $row['total_num'] - $row['stock_num'] + $params['stock_num'];
                $params['start_time'] = strtotime($params['start_time']);
                $params['end_time'] = strtotime($params['end_time']);
                if ($params['expired_type'] == 1) {
                    if (!$params['start_time'] || !$params['end_time']) {
                        return $this->error('开始时间和结束时间都不能为空');
                    }
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    //会员专享
//                    CouponVip::del($ids);
//                    if ($params['vip'][0]) {
//                        CouponVip::add($ids, $params['vip']);
//                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("coupon_vip", $coupon_vips);
        return $this->view->fetch();
    }
}
